﻿using Janus.BaseEntitys;
using Janus.Cores.Extension;
using Janus.Cores.Linq;
using Janus.Cores.Tools;
using Janus.Mes.DTO;
using Janus.Mes.Services.Interface;
using Janus.Mes.VO;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web.Mvc;
using Newtonsoft.Json;
using System.Diagnostics;
using Janus.Cores.Resources;

namespace Janus.Mes.WebClient.Areas.BaseData.Controllers.Calendar
{
    public partial class CalendarController : BaseController
    {
        #region 列表
        /// <summary>
        /// 工作日历首页（返回数据列表）
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Index()
        {
            return View(GetList(new FormCollection()));
        }

        /// <summary>
        /// 返回查询数据
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Index(FormCollection collection)
        {
            return View(GetList(collection));
        }

        #endregion

        #region 新增
        /// <summary>
        /// 新增工作日历
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Create()
        {
            CalendarVO calendar = new CalendarVO();
            calendar = base.InitModel<CalendarVO>(calendar);
            return View(calendar);
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public string Create(FormCollection form)
        {
            try
            {
                var result = false;
                CalendarVO model = new CalendarVO();
                model = base.SetModel<CalendarVO>(form);

                string json = model.YearContentJson;
                json = json.Remove(json.LastIndexOf(","), 1);
                List<CalendarVO> lstCldrVO = JsonConvert.DeserializeObject<List<CalendarVO>>(json);
                foreach (var item in lstCldrVO)
                {
                    item.Year = model.Year;
                    item.WorkCCode = model.WorkCCode;
                }

                List<CalendarDTO> lstCldrDTO = AutoMapper.Mapper.DynamicMap<List<CalendarDTO>>(lstCldrVO);
                result = CalendarServices.Add(lstCldrDTO);
                if (result)
                {
                    ajaxStr = base.AjaxResultSucess;
                }
                else
                {
                    ajaxStr = base.AjaxResultFail;
                }
            }
            catch (Exception ex)
            {
                base.ExceptionHand(ex);
                ajaxStr = base.AjaxResultFail;
            }
            return "{" + ajaxStr + "}";
        }

        #endregion

        #region 修改
        /// <summary>
        /// 修改工作日历
        /// </summary>
        /// <param name="id">年份</param>
        /// <param name="pk2">工作中心编码</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Edit(string id, string pk2, string pk3)
        {
            CalendarVO calendar = new CalendarVO();
            int year = -1;
            year = int.TryParse(id, out year) ? year : -1;
            string workCCode = pk2;
            string workCName = pk3;
            ViewBag.IsView = (Request.QueryString["action"] == "view") ? "1" : "0";
            if (!string.IsNullOrEmpty(id) && workCCode.IsNotEmpty())
            {
                Querier query = new Querier("WorkCCode = {@0} and Year = {@1}", new List<object>() { workCCode, year });
                var model = CalendarServices.FindOne(query);
                calendar = model.ToEntity<CalendarVO>();
            }
            else
            {
                calendar.Year = year;
                calendar.WorkCCode = workCCode;
            }
            calendar.WorkCName = workCName;

            return View(calendar ?? new CalendarVO());
        }

        [HttpPost]
        public string Edit(FormCollection form)
        {
            try
            {
                var result = false;
                CalendarVO model = new CalendarVO();
                model = base.SetModel<CalendarVO>(form);

                string json = model.YearContentJson;
                json = json.Remove(json.LastIndexOf(","), 1);
                List<CalendarVO> lstCldrVO = JsonConvert.DeserializeObject<List<CalendarVO>>(json);
                foreach (var item in lstCldrVO)
                {
                    item.Year = model.Year;
                    item.WorkCCode = model.WorkCCode;
                }

                List<CalendarDTO> lstCldrDTO = AutoMapper.Mapper.DynamicMap<List<CalendarDTO>>(lstCldrVO);
                result = CalendarServices.Save(lstCldrDTO);
                if (result)
                {
                    ajaxStr = base.AjaxResultSucess;
                }
                else
                {
                    ajaxStr = base.AjaxResultFail;
                }
            }
            catch (Exception ex)
            {
                base.ExceptionHand(ex);
                ajaxStr = base.AjaxResultFail;
            }
            return "{" + ajaxStr + "}";
        }

        /// <summary>
        /// 获取一年日历的数据
        /// </summary>
        /// <returns></returns>
        public ActionResult CldrContent()
        {
            List<CalendarVO> lstCalendar = new List<CalendarVO>();
            string sYear = Request.QueryString["syear"];
            string sWorkCCode = Request.QueryString["sworkccode"];
            string isView = Request.QueryString["isView"];
            int year = -1;
            year = int.TryParse(sYear, out year) ? year : -1;
            if (year > DateTime.MinValue.Year)
            {
                if (sWorkCCode.IsNotEmpty())
                {
                    //如果工作中心不为空，查询指定年份和指定工作中心一年的数据
                    lstCalendar = GetWorkCenterCalendar(year, sWorkCCode);
                }
                else
                {
                    //如果工作中心为空，则生成指定年份的默认数据
                    lstCalendar = GenerateWorkCenterCalender(year);
                }
            }
            ViewBag.IsViewAction = isView;
            ViewBag.CurrentYear = sYear;
            return View(lstCalendar);
        }
        #endregion

        #region 删除
        /// <summary>
        /// 删除工作日历
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public string Delete(string id, string pk2, string pk3)
        {
            try
            {
                int year = -1;
                year = int.TryParse(id, out year) ? year : -1;
                //当前年份和历史年份的数据不允许删除
                if (year <= DateTime.Now.Year)
                {
                    ajaxStr = string.Format(HelperCommon.AJAXFORMAT, 300, string.Format(ResourcesManager.CldrHisDeleteTip, year, pk3), navTabId, "", "");
                }
                //todo 已有生产排程的年份不允许删除
                else
                {
                    Querier query = new Querier("WorkCCode = {@0} and Year = {@1}", new List<object>() { pk2, year });
                    var result = CalendarServices.Delete(query);
                    ajaxStr = result ? base.AjaxDeleteSucess : base.AjaxResultFail;
                }
            }
            catch (Exception ex)
            {
                ExceptionHand(ex);
                ajaxStr = base.AjaxResultFail;
            }

            return "{" + ajaxStr + "}";
        }
        #endregion

        #region 复制
        [HttpGet]
        public ActionResult Copy()
        {
            CalendarVO calendar = new CalendarVO();
            return View(calendar);
        }

        [HttpPost]
        public string Copy(FormCollection form)
        {
            try
            {
                var result = false;
                CalendarVO model = new CalendarVO();
                model = base.SetModel<CalendarVO>(form);

                model.Year = 2016;
                model.WorkCCode = "S001";
                model.TargetWorkCCode = "S002";
                model.Creator = "admin";
                model.CreatorCode = "admincode";

                CalendarDTO dto = AutoMapper.Mapper.DynamicMap<CalendarDTO>(model);
                result = CalendarServices.CopyInsert(dto);

                //string json = model.YearContentJson;
                //json = json.Remove(json.LastIndexOf(","), 1);
                //List<CalendarVO> lstCldrVO = JsonConvert.DeserializeObject<List<CalendarVO>>(json);
                //foreach (var item in lstCldrVO)
                //{
                //    item.Year = model.Year;
                //    item.WorkCCode = model.WorkCCode;
                //}

                //List<CalendarDTO> lstCldrDTO = AutoMapper.Mapper.DynamicMap<List<CalendarDTO>>(lstCldrVO);
                //result = CalendarServices.Save(lstCldrDTO);
                if (result)
                {
                    ajaxStr = base.AjaxResultSucess;
                }
                else
                {
                    ajaxStr = base.AjaxResultFail;
                }
            }
            catch (Exception ex)
            {
                base.ExceptionHand(ex);
                ajaxStr = base.AjaxResultFail;
            }
            return "{" + ajaxStr + "}";
        }

        /// <summary>
        /// 级联获取指定年份设置了工作日历的工作中心
        /// </summary>
        /// <returns></returns>
        public string GetHasCalenderList()
        {
            string json = "[";
            string sYear = Request.QueryString["selectyear"];
            int year = -1;
            year = int.TryParse(sYear, out year) ? year : -1;
            if (year > 0)
            {
                Querier query = new Querier().Where("Year = {@0}", year).OrderBy<VwCalendarSumDTO>(c => c.WorkCCode);
                var result = CalendarServices.FindAll(query);
                foreach (var item in result)
                {
                    json += "['" + item.WorkCCode + "','" + item.WorkCName + "'],";
                }
            }
            if (json.Length > 2)
            {
                //如果查询有数据，则清除最后拼接的逗号
                json = json.Remove(json.Length - 1, 1);
            }
            json += "]";
            return json;
        }
        #endregion

        #region 主键是否存在
        [HttpPost]
        public string IsExist()
        {
            string data = Request["data"];
            Querier query = new Querier(" Year={@0} and WorkCCode={@0} and CDate={@0} ", new List<object>() { data });
            bool result = CalendarServices.IsExists(query);
            if (!result)
            {
                ajaxStr = base.AjaxResultSucess;
            }
            else
            {
                ajaxStr = base.AjaxResultFail;
            }
            return "{" + ajaxStr + "}";
        }
        #endregion

        #region 私有方法
        /// <summary>
        /// 获取工作日历统计列表
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        protected IEnumerable<VwCalendarSumVO> GetList(FormCollection collection)
        {
            var searchParma = base.SearchPara<VwCalendarSumDTO>(collection);
            if (searchParma.Model.Year > 0)
            {
                searchParma.Queriers.Where("Year = {@0}", searchParma.Model.Year);
            }
            if (searchParma.Model.WorkCCode.IsNotEmpty())
            {
                searchParma.Queriers.Where("WorkCCode = {@0}", searchParma.Model.WorkCCode);
            }

            //只能查看前5年及以后的年份数据
            searchParma.Queriers.Where("Year > {@0}", DateTime.Now.Year - 6);
            //按照年份倒序，工作中心升序排列
            searchParma.Queriers.OrderDescBy<VwCalendarSumDTO>(c => c.Year).OrderBy<VwCalendarSumDTO>(c=>c.WorkCCode);

            var result = base.FindAll<VwCalendarSumDTO>(searchParma, VwCalendarSumServices);
            if (result != null && (!result.ErrorMessage.IsNotEmpty()))
            {
                var lst = result.Result.ToEntitys<VwCalendarSumVO>();
                return lst;
            }
            else
            {
                return new List<VwCalendarSumVO>();
            }
        }

        /// <summary>
        /// 获取指定年份和工作中心的日历数据
        /// </summary>
        /// <param name="year">年份</param>
        /// <param name="workCCode">工作中心编码</param>
        /// <returns></returns>
        protected List<CalendarVO> GetWorkCenterCalendar(int year, string workCCode)
        {
            List<CalendarVO> lstCalendar = new List<CalendarVO>();
            Querier query = new Querier();
            query.Where("WorkCCode={@0}", workCCode).Where("Year ={@1}", year).OrderBy<CalendarDTO>(c => c.CDate);
            IList<CalendarDTO> lstDTO = CalendarServices.FindAll(query);
            if (lstDTO != null && lstDTO.Count > 0)
            {
                lstCalendar = AutoMapper.Mapper.DynamicMap<List<CalendarVO>>(lstDTO);
            }
            return lstCalendar ?? new List<CalendarVO>();
        }

        /// <summary>
        /// 生成指定年份默认的日历
        /// </summary>
        /// <param name="year">年份</param>
        /// <returns></returns>
        protected List<CalendarVO> GenerateWorkCenterCalender(int year)
        {
            List<CalendarVO> lstCalendar = new List<CalendarVO>();
            List<int> lstMonthDays = CalendarHelper.GetEachMonthDays(year);
            DateTime tempDate = DateTime.MinValue;
            int dayOfWeek = -1;
            for (int i = 0; i < 12; i++)
            {
                for (int j = 0; j < lstMonthDays[i]; j++)
                {
                    tempDate = new DateTime(year, i + 1, j + 1);
                    dayOfWeek = (int)tempDate.DayOfWeek;
                    lstCalendar.Add(new CalendarVO
                    {
                        Year = year,
                        CDate = tempDate,
                        Ctype = (dayOfWeek == 0 || dayOfWeek == 6) ? 2 : 1
                    });
                }
            }
            return lstCalendar;
        }
        #endregion

    }

}

